<template>
    <div>
        <el-dialog :title="dialogInfo.isAdd ? '添加商品管理' : '编辑商品管理'" :visible.sync="dialogInfo.isShow"
            :before-close="cancel" center @opened="createEdit">
            <el-form :model="goodsInfo" :rules="rules" ref="goodsInfo">
                <el-form-item label="一级分类" :label-width="formLabelWidth" prop="first_cateid">
                    <el-select v-model="goodsInfo.first_cateid" placeholder="请选择" @change="changeCate(false)">
                        <el-option v-for="item in catelist" :value="item.id" :key="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="二级分类" :label-width="formLabelWidth" prop="second_cateid">
                    <el-select v-model="goodsInfo.second_cateid" placeholder="请选择">
                        <el-option v-for="item in secondArr" :value="item.id" :key="item.id" :label="item.catename">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="商品名称" :label-width="formLabelWidth" prop="goodsname">
                    <el-input v-model="goodsInfo.goodsname" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="商品价格" :label-width="formLabelWidth" prop="price">
                    <el-input v-model="goodsInfo.price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="市场价格" :label-width="formLabelWidth" prop="market_price">
                    <el-input v-model="goodsInfo.market_price" autocomplete="off"></el-input>
                </el-form-item>
                <el-form-item label="图片" :label-width="formLabelWidth">
                    <el-upload action="#" list-type="picture-card" :auto-upload="false" :limit="1" :file-list="fileList"
                        :on-preview="onPreview" :on-remove="handleRemove" :on-change="onChange" :on-exceed="onExceed">
                        <i class="el-icon-plus"></i>
                    </el-upload>
                    <el-dialog :visible.sync="dialogVisible">
                        <img width="100%" :src="dialogImageUrl" alt="" />
                    </el-dialog>
                </el-form-item>
                <el-form-item label="商品规格" :label-width="formLabelWidth" prop="specsid">
                    <el-select v-model="goodsInfo.specsid" placeholder="请选择" @change="changeSpecs(false)">
                        <el-option v-for="item in specslist" :value="item.id" :key="item.id" :label="item.specsname">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="规格属性" :label-width="formLabelWidth" prop="specsattr">
                    <!-- multiple 是否多选 -->
                    <el-select multiple v-model="goodsInfo.specsattr" placeholder="请选择">
                        <el-option v-for="item in specsArr" :value="item" :key="item" :label="item"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="是否新品" :label-width="formLabelWidth">
                    <el-radio v-model="goodsInfo.isnew" :label="1">是</el-radio>
                    <el-radio v-model="goodsInfo.isnew" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="是否热卖" :label-width="formLabelWidth">
                    <el-radio v-model="goodsInfo.ishot" :label="1">是</el-radio>
                    <el-radio v-model="goodsInfo.ishot" :label="2">否</el-radio>
                </el-form-item>
                <el-form-item label="商品描述" :label-width="formLabelWidth">
                    <div id="edit"></div>
                </el-form-item>
                <el-form-item label="状态" :label-width="formLabelWidth">
                    <el-switch v-model="goodsInfo.status" active-color="#13ce66" inactive-color="#ff4949"
                        :active-value="1" :inactive-value="2">
                    </el-switch>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="cancel">取 消</el-button>
                <el-button type="primary" @click="confirm">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
import { goodsadd, goodsinfo, goodsedit } from '../../request/api'
import { mapActions, mapGetters } from "vuex";
import wangEditor from 'wangeditor'
export default {
    props: ['dialogInfo'],
    data() {
        return {
            goodsInfo: {
                first_cateid: "", //一级分类编号
                second_cateid: "", //二级分类编号
                goodsname: "", //商品名称
                price: "", //商品价格
                market_price: "", //市场价格
                img: "", //商品图片（文件）
                description: "", //商品描述
                specsid: "", //商品规格编号
                specsattr: "", //商品规格属性
                isnew: 1, //是否新品1是2不是
                ishot: 1, //是否热卖1是2不是
                status: 1, //状态1正常2禁用
            },
            formLabelWidth: "120px", //label宽度
            dialogVisible: false,  //用于控制图片预览的显示隐藏
            //预览时调用的图片地址
            dialogImageUrl: "",
            fileList: [], //用于图片回显
            //设置二级分类数据
            secondArr: [],
            //规格属性
            specsArr: [],
            //设置一个编辑器的值
            edit: null,
            //规则验证
            rules: {
                goodsname: [
                    { required: true, message: "请输入商品名称", trigger: "blur" },
                    {
                        min: 2,
                        max: 15,
                        message: "长度在 2 到 15 个字符",
                        trigger: "blur",
                    },
                ],
                price: [{ required: true, message: "请输入商品价格", trigger: "blur" }],
                market_price: [
                    { required: true, message: "请输入市场价格", trigger: "blur" },
                ],
                first_cateid: [
                    { required: true, message: "请选择一级分类", trigger: "change" },
                ],
                second_cateid: [
                    { required: true, message: "请选择二级分类", trigger: "blur" },
                ],
                specsid: [
                    { required: true, message: "请选择商品规格", trigger: "change" },
                ],
                specsattr: [
                    { required: true, message: "请选择规格属性", trigger: "blur" },
                ],
            },

        };
    },
    computed: {
        ...mapGetters({
            catelist: 'cate/getCalist',
            specslist: 'specs/getSpecsList'
        })
    },
    mounted() {
        //组件一加载调用分类列表接口
        this.getCate()
        //规格属性列表的调用
        this.getSpecs()
    },
    methods: {
        //封装一个实例化富文本编辑器的方法
        createEdit() {
            //实例化插件
            this.edit = new wangEditor('#edit')
            //创建
            this.edit.create()
            //设置初始值
            this.edit.txt.html(this.goodsInfo.description)
            // console.log(this.edit, '编辑器');
        },
        ...mapActions({
            getCate: 'cate/changeCateAction',
            getSpecs: 'specs/getSpecsListAction',
            getCount: 'goods/getCountAction',
            getGoodsList: 'goods/getGoodsListAction'
        }),
        cancel() {
            this.$emit('cancel', false)
            this.reset()
        },
        //封装一个清空事件
        reset() {
            this.goodsInfo = {
                first_cateid: "", //一级分类编号
                second_cateid: "", //二级分类编号
                goodsname: "", //商品名称
                price: "", //商品价格
                market_price: "", //市场价格
                img: "", //商品图片（文件）
                description: "", //商品描述
                specsid: "", //商品规格编号
                specsattr: "", //商品规格属性
                isnew: 1, //是否新品1是2不是
                ishot: 1, //是否热卖1是2不是
                status: 1, //状态1正常2禁用
            },
            //调用清空验证的方法
            this.$refs.goodsInfo.resetFields();
            this.fileList = [];
            //当弹框关闭的时候，我们触发销毁
            this.edit.destroy()
        },
        changeCate(n) {
            // console.log(n, 'huixianl ');
            //思路就是用户选中数组的某一项跟双向数据绑定的值匹配，匹配成功找到下标索引，找到所在children
            let index = this.catelist.findIndex((item) => item.id == this.goodsInfo.first_cateid)
            // console.log(index, "index");
            this.secondArr = this.catelist[index].children;
            //清空二级分类的双向数据绑定的值
            if (!n) {
                this.goodsInfo.second_cateid = "";
            }
        },
        changeSpecs(n) {
            let index = this.specslist.findIndex((item) => item.id == this.goodsInfo.specsid)
            console.log(index);
            this.specsArr = this.specslist[index].attrs
            if (!n) {
                this.goodsInfo.specsattr = ""
            }
        },
        onExceed(files, fileList) {
            this.$message.warning(
                `当前限制选择 1 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length
                } 个文件`
            );
        },
        //封装一个查询一条数据的接口
        lookup(id) {
            goodsinfo({ id }).then((res) => {
                console.log(res.data);
                if (res.data.code == 200) {
                    this.goodsInfo = res.data.list;
                    //对图片进行数据回显
                    this.fileList = this.goodsInfo.img ? [{ url: this.goodsInfo.img }] : [];
                    this.goodsInfo.id = id;
                    //针对于规格属性进行结构转化
                    this.goodsInfo.specsattr = this.goodsInfo.specsattr.split(',')
                    //把商品描述的值赋值给编辑器
                    this.edit.txt.html(this.goodsInfo.description)
                    //重新调用change事件 目的实现 label的渲染
                    this.changeCate(true);
                    this.changeSpecs(true);
                    
                } else {
                    this.$message.error(res.data.msg);
                }
            })
        },
        //预览的回调函数
        onPreview(file) {
            console.log(file, "文件");
            //得到文件地址之后，把它赋值给要显示的属性
            this.dialogImageUrl = file.url
            //打开图片预览弹框
            this.dialogVisible = true;
        },
        // 移除图片的时候触发
        handleRemove(file, fileList) {
            console.log(file, "移除", fileList);
        },
        // 当文件发生变化的时候触发
        onChange(file, fileList) {
            console.log(file, "文件详情，change时候");
            //把文件详情赋值给图片地址
            this.goodsInfo.img = file.raw
        },
        // 确定事件
        confirm() {
            this.$refs.goodsInfo.validate((valid) => {
                if (valid) {
                    this.goodsInfo.specsattr = this.goodsInfo.specsattr ? this.goodsInfo.specsattr.join(",") : '';
                    //给商品描述赋值
                    this.goodsInfo.description = this.edit.txt.html()
                    if (this.dialogInfo.isAdd) {
                        goodsadd(this.goodsInfo).then((res) => {
                            if (res.data.code == 200) {
                                // 关闭  弹框  重置
                                this.cancel();
                                // 重新获取总条数
                                this.getCount();
                                // 重新调取列表
                                this.getGoodsList();
                                this.$message.success(res.data.msg);
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        })
                    } else {
                        goodsedit(this.goodsInfo).then((res) => {
                            if (res.data.code == 200) {
                                // 关闭  弹框  重置
                                this.cancel();
                                // 重新获取总条数
                                this.getCount();
                                // 重新调取列表
                                this.getGoodsList();
                                this.$message.success(res.data.msg);
                            } else {
                                this.$message.error(res.data.msg);
                            }
                        })
                    }
                } else {
                    this.$message.error("验证失败");
                    return false;
                }
            })
        }
    }
};
</script>

<style  scoped>
</style>
